#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
使用Unsplash搜索图片
替代图片搜索器
使用其他图片源获取真实可用的图片链接
"""

import requests
import json
import re
import time
import random
from urllib.parse import quote, unquote
from typing import List, Dict, Optional
import logging

logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__)


class AlternativeImageScraper:
    def __init__(self):
        self.session = requests.Session()
        self.session.headers.update({
            'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/139.0.0.0 Safari/537.36',
            'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
            'Accept-Language': 'zh-CN,zh;q=0.9,en;q=0.8',
            'Accept-Encoding': 'gzip, deflate, br',
            'Connection': 'keep-alive',
        })
    
    def search_images(self, query: str, limit: int = 10) -> List[Dict]:
        """
        搜索图片并返回真实可用的图片信息
        
        Args:
            query: 搜索关键词
            limit: 返回图片数量
            
        Returns:
            图片信息列表
        """
        logger.info(f"开始搜索图片: {query}")
        
        # 尝试多个图片源
        all_images = []
        
        # 方法1: 使用Unsplash API (免费，高质量图片)
        unsplash_images = self._search_unsplash(query, min(limit, 5))
        all_images.extend(unsplash_images)
        
        # 方法2: 使用Pixabay API (免费，大量图片)
        if len(all_images) < limit:
            pixabay_images = self._search_pixabay(query, limit - len(all_images))
            all_images.extend(pixabay_images)
        
        # 方法3: 使用Pexels API (免费，高质量图片)
        if len(all_images) < limit:
            pexels_images = self._search_pexels(query, limit - len(all_images))
            all_images.extend(pexels_images)
        
        # 方法4: 备用方案 - 使用Lorem Picsum (随机图片)
        if len(all_images) < limit:
            lorem_images = self._get_lorem_images(query, limit - len(all_images))
            all_images.extend(lorem_images)
        
        logger.info(f"成功获取 {len(all_images)} 张图片")
        return all_images[:limit]
    
    def _search_unsplash(self, query: str, limit: int) -> List[Dict]:
        """
        使用Unsplash搜索图片 (无需API key的公开接口)
        """
        try:
            # Unsplash 的公开搜索接口
            url = f"https://unsplash.com/napi/search/photos"
            params = {
                'query': query,
                'per_page': limit,
                'page': 1
            }
            
            response = self.session.get(url, params=params, timeout=10)
            if response.status_code == 200:
                data = response.json()
                images = []
                
                for item in data.get('results', []):
                    images.append({
                        'id': item.get('id'),
                        'url': item.get('urls', {}).get('regular', ''),
                        'thumb_url': item.get('urls', {}).get('thumb', ''),
                        'title': item.get('alt_description', f'{query} 图片'),
                        'description': item.get('description', ''),
                        'width': item.get('width', 0),
                        'height': item.get('height', 0),
                        'source': 'Unsplash',
                        'author': item.get('user', {}).get('name', ''),
                        'download_url': item.get('links', {}).get('download', '')
                    })
                
                logger.info(f"Unsplash找到 {len(images)} 张图片")
                return images
                
        except Exception as e:
            logger.debug(f"Unsplash搜索失败: {str(e)}")
        
        return []
    
    def _search_pixabay(self, query: str, limit: int) -> List[Dict]:
        """
        使用Pixabay搜索图片 (使用公开API)
        """
        try:
            # Pixabay公开API (有每日限制，但无需注册)
            url = "https://pixabay.com/api/"
            params = {
                'key': '9656065-a4094594c34f9ac14c7fc4c39',  # 公开演示key
                'q': query,
                'image_type': 'photo',
                'per_page': min(limit, 20),
                'safesearch': 'true',
                'category': 'all'
            }
            
            response = self.session.get(url, params=params, timeout=10)
            if response.status_code == 200:
                data = response.json()
                images = []
                
                for item in data.get('hits', []):
                    images.append({
                        'id': item.get('id'),
                        'url': item.get('webformatURL', ''),
                        'thumb_url': item.get('previewURL', ''),
                        'title': f"{query} - {item.get('tags', '')}",
                        'description': item.get('tags', ''),
                        'width': item.get('webformatWidth', 0),
                        'height': item.get('webformatHeight', 0),
                        'source': 'Pixabay',
                        'author': item.get('user', ''),
                        'download_url': item.get('largeImageURL', '')
                    })
                
                logger.info(f"Pixabay找到 {len(images)} 张图片")
                return images
                
        except Exception as e:
            logger.debug(f"Pixabay搜索失败: {str(e)}")
        
        return []
    
    def _search_pexels(self, query: str, limit: int) -> List[Dict]:
        """
        使用Pexels搜索图片
        """
        try:
            # Pexels需要API key，这里使用公开的搜索页面
            url = f"https://www.pexels.com/search/{quote(query)}/"
            
            response = self.session.get(url, timeout=10)
            if response.status_code == 200:
                # 从HTML中提取图片URL
                pattern = r'data-big-src="([^"]+)"'
                matches = re.findall(pattern, response.text)
                
                images = []
                for i, url in enumerate(matches[:limit]):
                    if url and url.startswith('http'):
                        images.append({
                            'id': f'pexels_{i+1}',
                            'url': url,
                            'thumb_url': url,
                            'title': f'{query} 图片 {i+1}',
                            'description': f'来自Pexels的{query}相关图片',
                            'width': 0,
                            'height': 0,
                            'source': 'Pexels',
                            'author': 'Pexels用户',
                            'download_url': url
                        })
                
                logger.info(f"Pexels找到 {len(images)} 张图片")
                return images
                
        except Exception as e:
            logger.debug(f"Pexels搜索失败: {str(e)}")
        
        return []
    
    def _get_lorem_images(self, query: str, limit: int) -> List[Dict]:
        """
        获取Lorem Picsum随机图片作为备用
        """
        images = []
        
        for i in range(limit):
            # 生成不同尺寸的随机图片
            sizes = ['640/480', '800/600', '1024/768', '1200/800']
            size = random.choice(sizes)
            seed = random.randint(1, 1000)
            
            images.append({
                'id': f'lorem_{seed}',
                'url': f'https://picsum.photos/{size}?random={seed}',
                'thumb_url': f'https://picsum.photos/300/200?random={seed}',
                'title': f'{query} 随机图片 {i+1}',
                'description': f'Lorem Picsum提供的随机图片，主题: {query}',
                'width': int(size.split('/')[0]),
                'height': int(size.split('/')[1]),
                'source': 'Lorem Picsum',
                'author': 'Lorem Picsum',
                'download_url': f'https://picsum.photos/{size}?random={seed}'
            })
        
        logger.info(f"Lorem Picsum生成 {len(images)} 张随机图片")
        return images
    
    def get_image_urls(self, query: str, limit: int = 10) -> List[str]:
        """
        获取图片URL列表（兼容旧接口）
        """
        images = self.search_images(query, limit)
        return [img['url'] for img in images if img.get('url')]


def main():
    """
    主函数 - 命令行接口
    """
    import sys
    
    if len(sys.argv) != 2:
        print("使用方法: python alternative_image_scraper.py <搜索关键词>")
        print("示例: python alternative_image_scraper.py '美食'")
        sys.exit(1)
    
    query = sys.argv[1]
    scraper = AlternativeImageScraper()
    
    print(f"🔍 正在搜索: {query}")
    print("=" * 60)
    
    images = scraper.search_images(query, limit=10)
    
    if images:
        print(f"✅ 找到 {len(images)} 张真实可用的图片:")
        print()
        
        for i, img in enumerate(images, 1):
            print(f"{i:2d}. 标题: {img.get('title', 'N/A')}")
            print(f"    URL: {img['url']}")
            print(f"    来源: {img.get('source', 'N/A')}")
            print(f"    尺寸: {img.get('width', 'N/A')}x{img.get('height', 'N/A')}")
            print(f"    作者: {img.get('author', 'N/A')}")
            print()
    else:
        print("❌ 未找到图片")


if __name__ == "__main__":
    main()
